<template>
  <view>
    <uni-popup ref="popup" @maskClick="closePop">
      <view class="popup-wrap">
        <view class="header-wrap">
          <text>审核</text>
          <uni-icons class="close-icon" @click="closePop" type="closeempty" size="20px" color="#CCCCCC" />
        </view>
        <view class="content-wrap">
          <view class="item">
            <view><text style="color:#FF4D4F">*</text>煤种</view>
            <view>
              <uni-data-select ref="selectOneRef" v-model="relId" :localdata="productList" :class="{'readonly-select': isFromPlan}"
                @change="changeProduct"></uni-data-select>
            </view>
          </view>
          <view class="item">
            <view><text style="color:#FF4D4F">*</text>卸货地址
              <text class="create-link" @click="goToAddAddress">去创建>></text>
            </view>
            <view>
              <uni-data-select ref="selectTwoRef" v-model="adressId" :localdata="addressList" :class="{'readonly-select': isFromPlan}"
                @change="changeAddress"></uni-data-select>
            </view>
          </view>
        <view class="item" v-if="showOneyear">
            <view>
              <text style="color:#FF4D4F" v-if="batchIdRequire">*</text>竞价派车单
            </view>
            <view>
              <uni-data-select ref="selectbatchIdRef"  v-model="batchId" :localdata="batchIdList" @change="changeBatchId"></uni-data-select>
            </view>
          </view>
          <view class="info-card" :show-header="true" v-if="showOneyear">
            <view class="info-item">
              <view class="info-label title">竞价派车单信息</view>
            </view>
            <view class="info-item">
              <view class="info-label">编号：</view>
              <view class="info-value">{{ binddingCards.biddingNo || '' }}</view>
            </view>
            <view class="info-item">
              <view class="info-label">完成进度：</view>
              <view class="info-value">{{ binddingCards.process || '' }}</view>
            </view>
            <view class="info-item">
              <view class="info-label">预估剩余量：</view>
              <view class="info-value">{{ binddingCards.forecastSurplusAmount || '' }}</view>
            </view>
            <view class="info-item">
              <view class="info-label">开始时间：</view>
              <view class="info-value">{{ binddingCards.startTime || '' }}</view>
            </view>
            <view class="info-item">
              <view class="info-label">结束时间：</view>
              <view class="info-value">{{ binddingCards.endTime || '' }}</view>
            </view>
          </view>
        </view>
        <view class="footer-wrap">
          <view @click="examineCancel">审核作废</view>
          <view class="pass" @click="examinePass">审核通过</view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>
<script>
import { toast, getButtonShow } from '@/utils/common.js';
  import {getTenantId} from '@/utils/auth'
  import { findProCusRelName, findcusAddressbyCusId, saleWaybillAudit, getBingddingWaybill } from '@/api/tranplan.js';
  export default {
    props: {
      show: {
        type: Boolean,
        default: true
      },
      parentId: {
        type: String
      },
      cusId: {
        type: String
      },
      auditDataObj: {
        type: Object,
        default: () => {}
      },
      showOneyear: {
        type: Boolean,
        default: false
      },
    },
    watch: {
      show(flag) {
        if (flag) {
          this.resetForm()
          if (this.auditDataObj?.relId) {
            this.$nextTick(() => {
              this.$nextTick
              this.isFromPlan = true
              this.planRelId = this.auditDataObj.relId
              this.relId = this.auditDataObj.proData[0].value
              this.productList = this.auditDataObj.proData
              this.adressId = this.auditDataObj.addressData[0].value
              this.addressList = this.auditDataObj.addressData
            })
          } else {
            this.isFromPlan = false
            this.findProCusRelName()
            this.findcusAddressbyCusId()
          }
          this.$refs.popup.open()
        } else {
          this.$refs.popup.close()
        }
      }
    },
    data() {
      return {
        relId: undefined,
        adressId: undefined,
        productList: [],
        addressList: [],
        flagShow: false,
        isFromPlan: false,
        planRelId: undefined,
        batchIdRequire: false,
        batchIdList: [],
        batchId:undefined,
        batchIdListOriginal: [],
        originalProducts: [],
        binddingCards: {
          biddingNo: '',
          process: '',
          forecastSurplusAmount: '',
          startTime: '',
          endTime: '',
        },
      }
    },
    methods: {
      async goToAddAddress() {
        this.flagShow = await getButtonShow('caixiaoduan:unloader');
        if (this.flagShow){
          this.$tab.navigateTo('/packageB/pages/mine/unloader/index');
          this.closePop()
        }else {
          toast('未配置该功能')
        }
      },
      closePop() {
        this.$emit('closePop')
        this.$refs.popup.close()
      },
      async changeProduct(value) {
        this.batchIdList = []
        this.relId = value
        if (this.showOneyear && !!this.relId && !!this.cusId) {
          let proId = this.originalProducts.filter(item => item.id == this.relId)[0].proId
          let res = await getBingddingWaybill({ cusId: this.cusId, proId: proId , enterId: getTenantId() })
          if (res.code == 200) {
            if (res.data.length > 0) {
              this.batchIdRequire = true
              this.batchIdListOriginal = res.data
              this.batchIdList = res.data.map(item => {
                return {
                  text: item.startTime.substring(2, 10) +
                      "至" +
                      item.endTime.substring(2, 10) +
                      "预估剩余货量" +
                      item.forecastSurplusAmount +
                      "吨",
                  value: item.batchId
                }
              })
              if (this.batchIdList.length === 1) {
                this.batchId = this.batchIdList[0].value
                this.binddingCards.biddingNo = this.batchIdListOriginal[0].biddingNo
                this.binddingCards.forecastSurplusAmount = this.batchIdListOriginal[0].forecastSurplusAmount
                this.binddingCards.startTime = this.batchIdListOriginal[0].startTime
                this.binddingCards.endTime = this.batchIdListOriginal[0].endTime
                this.binddingCards.process = ((this.batchIdListOriginal[0].transportAmount / this.batchIdListOriginal[0].planValue) * 100).toFixed(2) + "%"
              }
            } else {
              this.batchIdRequire = false
              this.batchIdList = []
              this.$nextTick(() => {
                this.batchId = undefined
                this.binddingCards = {
                  biddingNo: '',
                  forecastSurplusAmount: '',
                  startTime: '',
                  endTime: '',
                  process: ''
                }
                this.$refs.selectbatchIdRef?.clearVal()
              })
            }
          }
        }
      },
      changeAddress(value) {
        this.adressId = value
      },
      async findProCusRelName() {
        const res = await findProCusRelName({ cusId: this.cusId })
        if (res.code === 0) {
          const result = res.data || []
          this.originalProducts = result
          this.productList = this.getResultList(result, 'proName', 'id')
        }
      },
      async findcusAddressbyCusId() {
        const res = await findcusAddressbyCusId({ cusId: this.cusId })
        if (res.code === 0) {
          const result = res.data || []
          this.addressList = this.getResultList(result, 'cusAddress', 'id')
        }
      },
      getResultList(list, label, value) {
        return list.map(e => {
          return {
            text: e[label],
            value: e[value]
          }
        })
      },
      changeBatchId(value) {
        this.batchId = value
        this.batchIdListOriginal.forEach(item => {
          if (item.batchId == value) {
            this.binddingCards.biddingNo = item.biddingNo
            this.binddingCards.forecastSurplusAmount = item.forecastSurplusAmount
            this.binddingCards.startTime = item.startTime
            this.binddingCards.endTime = item.endTime
            this.binddingCards.process = ((item.transportAmount / item.planValue) * 100).toFixed(2) + "%"
          }
        })
      },
      async examineCancel() {
        if (!this.relId) {
          toast('请选择煤种')
          return
        }
        if (!this.adressId) {
          toast('请选择卸货地址')
          return
        }
        if (this.showOneyear && this.batchIdRequire && !this.batchId) {
          toast('请选择竞价派车单')
          return
        }
        const data = {
          id: this.parentId,
          status: 2,
          relId: this.isFromPlan ? this.planRelId : this.relId,
          adressId: this.adressId,
          batchId: this.showOneyear ? this.batchId : null
        }
        const res = await saleWaybillAudit(data)
        if (res.code === 0) {
          this.$refs.popup.close()
          this.$emit('examineCancel')
        } else {
          toast(res.msg)
        }
      },
      async examinePass() {
        if (!this.relId) {
          toast('请选择煤种')
          return
        }
        if (!this.adressId) {
          toast('请选择卸货地址')
          return
        }
        if (this.showOneyear && this.batchIdRequire && !this.batchId) {
          toast('请选择竞价派车单')
          return
        }
        const data = {
          id: this.parentId,
          status: 1,
          relId: this.isFromPlan ? this.planRelId : this.relId,
          adressId: this.adressId,
          batchId: this.showOneyear ? this.batchId : null
        }
        const res = await saleWaybillAudit(data)
        if (res.code === 0) {
          this.$emit('examinePass')
        } else {
          toast(res.msg)
        }
      },
      resetForm() {
        this.$nextTick(() => {
          this.batchIdRequire = false
          this.relId = undefined
          this.adressId = undefined
          this.productList = []
          this.addressList = []
          this.batchIdList = []
          this.batchIdListOriginal = []
          this.batchId = undefined
          this.binddingCards = {
            biddingNo: '',
            forecastSurplusAmount: '',
            startTime: '',
            endTime: '',
            process: ''
          }
          this.$refs.selectOneRef?.clearVal()
          this.$refs.selectTwoRef?.clearVal()
          this.$refs.selectbatchIdRef?.clearVal()
        })
      }
    }
  }
</script>
<style lang="scss" scoped>
  .popup-wrap {
    width: 300px;
    border-radius: 10px;
    background-color: #ffffff;
  }

  .header-wrap {
    height: 46px;
    position: relative;
    padding: 12px 20px;
    text-align: center;
    border-bottom: 1px solid #eaeaea;

    .close-icon {
      position: absolute;
      right: 20px;
    }

    text {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .content-wrap {
    padding: 24px;
    border-bottom: 1px solid #eaeaea;

    >.item+.item {
      margin-top: 20px;
    }
  }

  .footer-wrap {
    height: 50px;
    display: flex;

    >view {
      flex: 1;
      font-size: 15px;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    .pass {
      color: #409EFE;
    }

    >view+view {
      border-left: 1px solid #EAEAEA;
    }
  }
  .create-link {
    float: right; /* 将超链接浮动到右侧 */
    color: #409EFE; /* 设置超链接的颜色 */
    text-decoration: underline; /* 可选：添加下划线 */
    margin-left: 8px; /* 可选：与“卸货地址”文本保持一定间距 */
  }
  // 模仿uni-card样式的info-card
  $border-color: #EBEEF5;
  $shadow-base: 0 0px 6px 1px rgba(165, 165, 165, 0.2);
  $main-color: #3a3a3a;
  $base-color: #6a6a6a;
  $card-spacing: 10px;
  $card-title: 15px;
  $card-content-color: $base-color;

  .info-card {
    margin: 20px 0 0 0;
    width: 100%;
    padding: 0;
    border-radius: 4px;
    overflow: hidden;
    background-color: #fff;
    border: 1px solid $border-color;
    box-shadow: $shadow-base;

    // 卡片标题样式
    &[title]::before {
      content: attr(title);
      display: block;
      padding: $card-spacing;
      font-size: $card-title;
      color: $main-color;
      font-weight: 500;
      border-bottom: 1px solid $border-color;
      box-sizing: border-box;
    }

    // 卡片内容样式
    &[show-header="true"] {
      >.info-item:first-child {
        margin-top: 0;
      }
    }
  }

  // 信息项样式
  .info-item {
    display: flex;
    padding: 12px $card-spacing;
    margin-top: 0;
    font-size: 14px;
    color: $card-content-color;
    line-height: 22px;
    border-bottom: 1px solid $border-color;

    &:last-child {
      border-bottom: none;
    }

    .info-label {
      width: 86px;
      flex-shrink: 0;
      color: #606266;
      font-size: 14px;

    }
      .title{
        width: 100%;
        text-align: center;
        height: 20px;
        line-height: 20px;
      }

    .info-value {
      flex: 1;
      text-align: left;
      color: #303133;
      font-size: 14px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
</style>